<template lang='pug'>
  Modal.mail-detail(v-model="show" fullscreen title="再次编辑邮件" :class="loading?'ov-hide':''")
    Spin.z-99(v-if="loading" size="large" fix)
    div(@click="dropdownShow = false")
      Form.ivu-row(ref="formData" :model="formData" :label-width="90")
        FormItem.ivu-col.ivu-col-span-24.mb-10(label="主题：" prop="")
          Input(v-model="formData.theme" placeholder="请输入" clearable)
        FormItem.ivu-col.ivu-col-span-24.mb-5(label="收件人：")
          .mail-inbox(@click.stop="inputFocus")
            template(v-for="item in toInboxList")
              //- (closable @on-close="handleClose(item.id)")
              Tag {{item.name}}
            input.searchinput(ref="searchinput" v-model="serachValue" type="text" @keyup="inputKeyUp" autocomplete="off" spellcheck="false" :style="{width:inputWidth}")
          div.mail-select
            span.mr-5(@click="showModal") 选择
            Icon(type="ios-add-circle")
          .ivu-select-multiple
            .ivu-select-dropdown(v-show="dropdownShow" style="width:100%" @click.stop="dropdownShow = true")
              ul.ivu-select-dropdown-list
                li.ivu-select-item(v-for="(item, index) in searchResult" :key="index" @click="chooserUser(item.id, item.name, item.powerType)" :class="{'ivu-select-item-selected ivu-select-item-focus' : isChecked(item.id)}") {{item.name}}
                  span(v-if="item.companyName || item.positionName") （
                  span {{item.companyName}}
                  span(v-if="item.positionName") ，
                  span {{item.positionName}}
                  span(v-if="item.companyName || item.positionName") ）
        FormItem.ivu-col.ivu-col-span-24.mb-5(label="")
          Upload(
            :headers="headers"
            :show-upload-list="false"
            :multiple="true"
            :action="uploadBaseUrl + '/MailManage/Upload?categoryName=邮件管理'"
            :on-success="attachmentsBefore"
          )
            .cursor-pointer
              i.font-18.iconfont.icon-fujian
              span 添加附件
          template(v-for="(item, index) in formData.attaList")
            .my-tag.mr-20
              .my-tag-inner {{item.name}}
              .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFileOld(item.id)")
          //- template(v-for="(item, index) in file")
          //-   .my-tag.mr-20
          //-     .my-tag-inner {{item.Name}}
          //-     .img-close.ivu-icon.ivu-icon-ios-close(@click="deleteFile(item.Id)")
        FormItem.ivu-col.ivu-col-span-24(label="正文：")
          editor(ref="editor" :value="formData.content")
    SelectUser(ref="select_user" @on-confrim="selectConfirm")
    template(slot="footer")
      Button(@click="show = false") 关闭
      Button.ml-20(type="primary" @click="sendMail") 发送
</template>

<script>
import MailApi from '../service.js'
import Cookies from 'js-cookie'
import Editor from '_c/editor'
import SelectUser from '../write-mail/modal/selectUser.vue'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import config from '@/config'

import { debounce } from '@/utils/debounce.js'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: 'edit-again',
  props: {
    mailId: String
  },
  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      uploadBaseUrl: baseUrl,
      show: false,
      loading: false,
      formData: {},
      dropdownShow: false,
      timer: null,
      inputWidth: '30px',
      serachValue: '',
      searchResult: [],
      toInboxList: [],
      file: []
    }
  },

  components: {
    SelectUser,
    Editor
  },

  computed: {
    // 是否存在
    isChecked () {
      return id => {
        return this.toInboxList.some(item => {
          return item.id === id
        })
      }
    }
  },

  beforeMount () {},

  mounted () {
    console.log(this.$store.state.user)
    // this.getDetail()
  },

  methods: {
    dropdownShowFn () {
      this.dropdownShow = false
    },
    openModal () {
      this.show = true
    },
    getEditAgainModel () {
      this.toInboxList = []
      this.$refs.select_user.cleanUp()
      MailApi.GetEditAgainModel({
        id: this.mailId
      }).then(res => {
        console.log(res)
        this.formData = res.data.data
        res.data.data.userDtoList.forEach(item => {
          this.$refs.select_user.addInboxUser({
            id: item.id,
            name: item.name,
            powerType: item.powerType
          })
          this.toInboxList.push({
            id: item.id,
            name: item.name,
            powerType: item.powerType
          })
        })
      })
    },
    inputFocus () {
      this.$refs.searchinput.focus()
    },
    chooserUser (id, name, powerType) {
      this.$refs.searchinput.blur()
      this.serachValue = ''
      let isHas = this.toInboxList.some(item => {
        return item.id === id
      })
      if (isHas) {
        this.toInboxList.splice(this.toInboxList.findIndex(item => item.id === id), 1)
        this.$refs.select_user.closeInboxUser(id)
      } else {
        this.toInboxList.push({
          id: id,
          name: name,
          powerType: powerType
        })
        this.$refs.select_user.addInboxUser({
          id: id,
          name: name,
          powerType: powerType
        })
      }
    },
    selectConfirm (val) {
      this.toInboxList = val
      console.log(this.toInboxList)
    },
    handleClose (id) {
      this.toInboxList.splice(
        this.toInboxList.findIndex(item => item.id === id),
        1
      )
      this.$refs.select_user.closeInboxUser(id)
    },
    inputKeyUp (e) {
      let str = e.target.value
      if (str.length < 1) {
        this.inputWidth = '30px'
      } else {
        this.inputWidth = str.length * 20 + 'px'
      }
      this.searchFn()
    },
    searchFn: debounce(function () {
      this.serachUser()
    }, 800),
    // 搜索收件人
    serachUser () {
      MailApi.GetMailUserList({ name: this.serachValue }).then(res => {
        this.dropdownShow = true
        this.searchResult = res.data.data.map(item => {
          return {
            id: item.id,
            name: item.name,
            powerType: item.powerType,
            companyName: item.companyName,
            positionName: item.positionName
          }
        })
      })
    },
    showModal () {
      this.$refs.select_user.arr_0_inbox = []
      this.$refs.select_user.arr_1_inbox = []
      this.$refs.select_user.arr_2_inbox = []
      this.toInboxList.forEach(item => {
          this.$refs.select_user.addInboxUser({
            id: item.id,
            name: item.name,
            powerType: item.powerType
          })
        })
      this.$refs.select_user.showFn()
    },
    attachmentsBefore (response, file, fileList) {
      if (response.Success) {
        this.file.push(response.Data)
        this.formData.attaList.push({
          id: response.Data.Id,
          name: response.Data.Name
        })
      } else {
        this.$Message.error(response.Message)
      }
    },
    deleteFile (id) {
      this.file.splice(this.file.findIndex(item => item.Id === id), 1)
      MailApi.DeleteAnnex({
        id: id
      }).then(res => {
      })
    },
    deleteFileOld (id) {
      this.formData.attaList.splice(this.formData.attaList.findIndex(item => item.id === id), 1)
    },
    sendMail () {
      let data = {
        theme: '',
        originalId: '',
        name: '',
        fromId: '',
        attaIdList: [],
        content: '',
        toIdList: []
      }
      if (!this.formData.theme) {
        this.$Message.warning('请输入邮件主题')
      } else if (this.toInboxList.length < 1) {
        this.$Message.warning('请选择收件人')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '<p>确认发送？</p>',
          onOk: () => {
            this.toInboxList.forEach(item => {
              data.toIdList.push(item.id)
            })
            data.theme = this.formData.theme
            data.name = this.formData.name
            data.fromId = this.formData.fromId
            data.content = this.$refs.editor.editor.txt.html()
            data.attaIdList = this.formData.attaList.map(item => {
              return item.id
            })
            MailApi.addMail(data).then(res => {
              if (res.data.success) {
                this.$Message.success(res.data.message)
                this.show = false
                this.$emit('get-list')
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 5,
                  closable: true
                })
              }
            })
          },
          onCancel: () => {}
        })
      }
    }
  },

  watch: {
    mailId (val) {
      console.log(val)
      this.getEditAgainModel()
    }
  }
}
</script>
<style lang="less">
.mail-attr-list{
  .ivu-list-header{
    background-color: #f2f2f2;
  }
  .ivu-list-items{
    padding-left: 38px;
    .ivu-list-item{
      padding-left: 0;
      padding-right: 70px;
      position: relative;
      .iconfont{
        position: absolute;
        top: 10px;
        left: -24px;
        color: #f25149;
        font-size: 18px;
      }
      .down{
        color: #0dc2ff;
        // position: absolute;
        // top: 12px;
        // right: 30px;
        margin-left: 20px;
        cursor: pointer;
      }
    }
  }
}
.mail-detail{
  &.ov-hide{
    .ivu-modal-body{
      overflow: hidden !important;
    }
  }
  .ivu-modal-wrap {
    top: 5%;
    bottom: 5%;
    left: 5%;
    right: 5%;
  }
  .reply-list{
    .ivu-timeline-item-tail{
      border-color: #0dc2ff;
      left: 7px;
    }
    .ivu-timeline-item-head.ivu-timeline-item-head-blue{
      width: 15px;
      height: 15px;
      background-color: #0dc2ff;
      border: 4px solid #fff;
    }
  }
}
.mail-content{
  th,td{
    border: 1px solid #eee;
    margin: -1px;
  }
  img{
    width: auto;
  }
}
</style>

<style lang='less' scoped>
.ivu-select-item{
  span{
    color: #999;
    font-size: 12px;
  }
}
.searchinput{
  border: none;
  height: 36px;
}
.mail-select {
  position: absolute;
  top: 0;
  right: 18px;
  z-index: 9;
  height: 100%;
  line-height: 1;
  display: flex;
  align-items: center;
  color: #0dc2ff;
  cursor: pointer;
}
.cursor-pointer {
  display: flex;
  align-items: center;
  color: #0bc2ff;
}
.mail-inbox {
  background-color: #fff;
  min-height: 36px;
  border-radius: 8px;
  border-color: rgba(255, 255, 255, 0);
  -webkit-box-shadow: 1px 2px 3px rgba(0, 130, 174, 0.05);
  box-shadow: 1px 2px 3px rgba(0, 130, 174, 0.05);
  padding-left: 15px;
  padding-right: 80px;
}
</style>
